package com.skins{
	import com._public._net.FaceLibrary;
	import com.skins.data.PhoneInfo;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.text.StyleSheet;
	import flash.text.TextFormat;

	/**
	 * MonkeyLib组件包样式配置表加载
	 * @author WZH(shch8.com)
	 */
	public class MkConfig extends EventDispatcher {
		private static var Instance:MkConfig = new MkConfig;

		public static function getInstance():MkConfig {
			return Instance;
		}
		private var loader:URLLoader = new URLLoader();
		private var _configPath:String = "";
		private var _configList:Array;
		private var swfList:Array;
		private var _configData:XML;
		/**
		 * 样式表对象数据
		 */
		public var dataObj:Object = {};

		/**
		 * 设置皮肤加载配置表
		   <data img="skin/default/img/">
		   <css path="skin/default/config.xml"/>
		   <css path="skin/default/component.xml"/>
		   <swf path="skin/default/main.swf"/>
		   <swf path="skin/default/phcomponent.swf"/>
		   </data>
		 */
		public function set skinConfig(value:String):void {
			var req:URLRequest = new URLRequest(value);
			loader.load(req);
			loader.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
			loader.addEventListener(Event.COMPLETE, getSetData);
		}

		/**
		 * 添加配置文件
		 * @param data
		 *
		 */
		public function appendConfigData(data:XML):void {
			toObject(data);
		}

		/**
		 * 样式配置数据
		 * 修改为Object方式获取数据 2012/12/7 14:15
		 */
		public function set configData(value:XML):void {
			_configData = value;
			dataObj = {};
			toObject(value)
		}

		public function get configData():XML {
			return _configData
		}

		//样式表转化为Object
		private function toObject(data:XML):void {
			var xmlList:XMLList;
			var propertyname:String;
			var propertyvalue:String;
			var obj:Object;
			var len:uint = data.child("*").length();
			for (var j:uint; j < len; j++){
				xmlList = data.child(j);
				obj = {};
				for (var i:int = 0; i < xmlList.attributes().length(); i++){
					propertyname = xmlList.attributes()[i].name(); //对应的属性名 
					propertyvalue = xmlList.attributes()[i]; //对应的属性值 000
					if (propertyname == "color")
						propertyvalue = "#" + propertyvalue;
					obj[propertyname] = propertyvalue; //将每个属性值对应的存放在OBJECT中 
				}
//				if (dataObj[xmlList.@id] != null) {
//					trace(xmlList.@id + "  重名，请修正样式表");
//				}
				dataObj[xmlList.@id] = obj;
			}
		}

		//获取配置表，做初始设置
		private function getSetData(e:Event):void {
			loader.removeEventListener(IOErrorEvent.IO_ERROR, errorHandler);
			loader.removeEventListener(Event.COMPLETE, getSetData);
			var xml:XML = XML(loader.data);
			Skin.librarys.imgDefaultPath = xml.@img; //设置图片默认加载路径
			_configList = [];
			swfList = [];
			for (var i:uint; i < xml.child("*").length(); i++){
				if (xml.child(i).name() == "css"){
					_configList.push(xml.child(i).@path);
				}
				if (xml.child(i).name() == "swf"){
					swfList.push(xml.child(i).@path);
				}
			}
			loadSwfList();
		}

		//加载SWF皮肤文件
		private function loadSwfList():void {
			if (swfList.length == 0){
				loadPathList();
				return;
			}
			Skin.faceLibrary = new FaceLibrary;
			Skin.faceLibrary.addEventListener(Event.COMPLETE, swfLoadComplete);
			Skin.faceLibrary.load(swfList[0]); //采用SWF皮肤时，加载库
			swfList.shift();
		}

		private function swfLoadComplete(e:Event):void {
			if (swfList != null){
				if (swfList.length > 0){
					loadSwfList();
					return;
				}
			}
			//完成swf列表加载,开始加载CSS文件
			loadPathList();
		}

		/**
		 * 样式表路径列表，多张样式表读取时使用
		 * 如：configPathList=["skin/default/config.xml","skin/default/module.xml"]
		 */
		public function set configPathList(value:Array):void {
			_configList = value;
			loadPathList();
		}

		//开始一加载每一个表
		private function loadPathList():void {
			configPath = _configList[0];
			_configList.shift();
		}

		/**
		 * 样式表路径，自动加载，完成后发布Event.COMPLETE事件
		 */
		public function set configPath(value:String):void {
			_configPath = value;
			var req:URLRequest = new URLRequest(value);
			loader = new URLLoader
			loader.load(req);
			loader.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
			loader.addEventListener(Event.COMPLETE, loaderCompleteHandler);
		}

		public function get configPath():String {
			return _configPath;
		}

		/**
		 * 获取样式组对像
		 * @param	cssID
		 * @return
		 */
		public function getStyle(cssID:String):Object {
			var obj:Object = dataObj[cssID];
			return obj == null ? {} : obj;
		}

		/**
		 * 获取样式值，复合皮肤可以加_css表示，将优先读取
		 * @param	cssID		样式组名称
		 * @param	cssValue	样式变量
		 * @return
		 */
		public function getStyleValue(cssID:String, cssValue:String):String {
			var obj:Object = getStyle(cssID);
			obj = obj[cssValue];
			return String(obj);
		}

		/**
		 * 获取文本样式对象
		 * @param	obj
		 * @return
		 */
		public function transform(obj:Object, minSize:int = 12):TextFormat {
			var style:StyleSheet = new StyleSheet();
			if (obj.fontSize == undefined)
				return style.transform(obj);
			var fmt:int = Math.round(obj.fontSize * (PhoneInfo.getInstance().scrWidth / PhoneInfo.getInstance().defaultWid));
			var txtFormat:TextFormat = style.transform(obj);
			if (fmt < minSize)
				fmt = minSize;
			txtFormat.size = fmt;
			return txtFormat;
		}

		private function errorHandler(e:IOErrorEvent):void {
			throw("加载失败，请设置正确的路径！错误地址:" + _configPath);
		}

		private function loaderCompleteHandler(e:Event):void {
			if (configData == null){
				configData = XML(loader.data)
			}
			appendConfigData(XML(loader.data));
			if (_configList != null){
				if (_configList.length > 0){
					loadPathList();
					return;
				}
			}
			_configList = _configList = null;
			this.dispatchEvent(new Event(Event.COMPLETE));
			loader.removeEventListener(IOErrorEvent.IO_ERROR, errorHandler);
			loader.removeEventListener(Event.COMPLETE, loaderCompleteHandler);
			loader = null;
		}
	}
}